import localforage from "localforage";
import axios from "axios";
import _ from "lodash";

//全局配置
/**
localforage.config({
  driver      : localforage.INDEXEDDB,
  name        : 'myApp',
  version     : 1.0,
  //size        : 4980736, // 数据库的大小，单位为字节。现仅 WebSQL 可用
  storeName   : 'keyvaluepairs', // 仅接受字母，数字和下划线
  description : 'some description'
});
 */

// 单个实例配置
const store = localforage.createInstance({
  name: "myApp", // 数据库名
  storeName: "kvCache", // 表名,仅接受字母，数字和下划线
  // 驱动顺序：优先 IndexedDB → WebSQL → localStorage
  //优雅降级策略，若浏览器不支持 IndexedDB 或 WebSQL，则使用 localStorage。
  driver: [localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE],
  //driver: localforage.INDEXEDDB, // 强制使用 IndexedDB
});

const storeKeys = {
  bigData: "bigData",
};

const expire = 10 * 60 * 1000;
const useCache = false;

const cacheCommon = {
  async setItem(key, value) {
    const raw = _.cloneDeep(value);
    if (useCache) {
      return await store.setItem(key, { data: raw, timestamp: Date.now() });
    }
    return await store.setItem(key, raw);
  },
  async getItem(key) {
    const cache = await store.getItem(key);

    if (!useCache) {
      return cache;
    }

    const now = Date.now();
    if (cache && now - cache.timestamp < expire) {
      return cache.data; // 命中缓存
    }
  },
  async removeItem(key) {
    return await store.removeItem(key);
  },
  async clear() {
    return await store.clear();
  },
};

export async function getBigData() {
  const key = storeKeys.bigData;
  // 先查缓存
  const cache = await cacheCommon.getItem(key);
  if (cache) {
    return cache;
  }
  const data = {};
  //const data = await fetchBigDataFromApi();
  // 存入缓存（不设置过期时间）
  await cacheCommon.setItem(key, data);
  return data;
}

// #region localStorage相关方法
export const setStorage = (key, data) => {
  return localStorage.setItem(key, data);
};

export const getStorage = (key) => {
  return localStorage.getItem(key);
};

export const clearStorage = (leu) => {
  return localStorage.removeItem(leu);
};
// #endregion
